package com.work.demo.threaddemo;

import cn.hutool.core.thread.ThreadUtil;

import java.util.concurrent.ExecutorService;

/**
 * @ClassName : VolatileTest
 * @Description :
 * @Author : LinYa
 * @Date: 2021/11/11  14:20
 */
public class VolatileTest {
	/**
	 * 方法1：加volatile关键字
	 */
	private boolean flag = true;
	/**
	 * 方法6：加volatile关键字
	 * 方法7：使用Integer
	 */
	private Integer count = 0;

	private void refresh() {
		flag = false;
		System.out.println(Thread.currentThread().getName() + "修改flag:" + flag);
	}

	private void load() {
		System.out.println(Thread.currentThread().getName() + "开始执行.....");
		while (flag) {
			count++;
			//方法2：使用内存屏障（Unsafe工具类）
			//UnsafeFactory.getUnsafe().storeFence;

			//方法3
			//Thread.yield();

			//方法4
			//System.out.println("-----");

			//方法5：给当前线程发放一个许可
			//LockSupport.unpark(Thread.currentThread());

		}
		System.out.println(Thread.currentThread().getName() + "跳出循环：count=" + count);
	}

	private ExecutorService createThread() {
		return ThreadUtil.newExecutor(5, 200, 200);
	}

	public static void main(String[] args) throws InterruptedException {
		VolatileTest test = new VolatileTest();
		ExecutorService thread = test.createThread();

		thread.execute(test::load);

		Thread.sleep(1000);

		thread.execute(test::refresh);
//		Thread threadA = new Thread(() ->test.load(), "threadA");
//		threadA.start();
//
//		Thread.sleep(1000);
//		Thread threadB = new Thread(() ->test.refresh(), "threadB");
//		threadB.start();
		//上面操作执行完后，终止所有线程
		thread.shutdown();


	}


}
